// utils/expireDateView.js
let utils = require('util.js')
Component({
  /**
   * 开启全局样式
   * **/
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的初始数据
   */
  data: {
    deadLine:"",
    activity_time: "",
    isOver:false,
    detail: {

    }
  },
  /**
   * 组件的属性列表
   * 
   */
  properties: {
    /**
     * 活动列表倒计时
     * **/
    countdownData: {
      type: String,
      value: '',
      observer: function(newVal, oldVal) {
        console.log(newVal)
      }
    },
    /**
     * 活动详情倒计时
     * **/
    activityCountdownData: {
      type: Object,
      value: '',
      observer: function (newVal, oldVal) {
        let that = this;
        console.log(newVal)
        that.setData({
          activity_time: newVal.activity_time,//截止时间
          isOver:newVal.isOver,
        })
        let deadLine = utils.formatUTCDate(that.data.activity_time);
        that.startCountDown(deadLine);
      }
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    startCountDown(dateStr) {
      this.setData({
        deadLine: dateStr
      })
      count_down(this)
    }
  }
})

function getOffsetDays(time1, time2) {
  var offsetTime = time2 - time1;
  if (offsetTime <= 0) {
    return 0
  } else {
    return Math.floor(offsetTime);
  }
}

function createDate(date) {
  var ps = date.split(" ");
  var pd = ps[0].split("-");
  var pt = ps.length > 1 ? ps[1].split(":") : [0, 0, 0];
  return new Date(pd[0], pd[1] - 1, pd[2], pt[0], pt[1], pt[2]);
}

/* 毫秒级倒计时 */
function count_down(that) {
  // 获取相隔天数
  var now = Date.now()
  var target = createDate(that.data.deadLine)
  var ms = getOffsetDays(now, target);
  date_format(ms, that)
  if (ms <= 0) {
    that.setData({
      isOver: true
    })
    // timeout则跳出递归
    that.triggerEvent('timeoutEvent')
    return;
  }
  setTimeout(function() {
    // 放在最后--
    ms -= 1000;
    count_down(that);
  }, 1000)
}
// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second, that) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  ///天数
  var days = fill_zero_prefix(Math.floor(second / (3600 * 24)));
  // 小时位
  var hr = fill_zero_prefix(Math.floor((second - days * (3600 * 24)) / 3600));
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - days * (3600 * 24) - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - days * (3600 * 24) - hr * 3600 - min * 60)); // equal to => var sec = second % 60;
  // // 毫秒位，保留2位
  // var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
  that.setData({
    days: days,
    hours: hr,
    mins: min,
    secs: sec,
  })
}
// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}